# -*- coding: utf8-*-


import uno,os,ghostscript
from os.path import abspath, isfile, splitext
from com.sun.star.beans import PropertyValue
from com.sun.star.task import ErrorCodeIOException
from com.sun.star.connection import NoConnectException

FAMILY_TEXT = "Text"
FAMILY_WEB = "Web"
FAMILY_SPREADSHEET = "Spreadsheet"
FAMILY_PRESENTATION = "Presentation"
FAMILY_DRAWING = "Drawing"
DEFAULT_OPENOFFICE_PORT = 8100
# ---------------------#
# Configuration Start #
# ---------------------#

# see http://wiki.services.openoffice.org/wiki/Framework/Article/Filter

# most formats are auto-detected; only those requiring options are defined here
IMPORT_FILTER_MAP = {
    "txt": {
        "FilterName": "Text (encoded)",
        "FilterOptions": "utf8"
    },
    "csv": {
        "FilterName": "Text - txt - csv (StarCalc)",
        "FilterOptions": "44,34,0"
    }
}

EXPORT_FILTER_MAP = {
    "pdf": {
        FAMILY_TEXT: {"FilterName": "writer_pdf_Export"},
        FAMILY_WEB: {"FilterName": "writer_web_pdf_Export"},
        FAMILY_SPREADSHEET: {"FilterName": "calc_pdf_Export"},
        FAMILY_PRESENTATION: {"FilterName": "impress_pdf_Export"},
        FAMILY_DRAWING: {"FilterName": "draw_pdf_Export"}
    },
    "html": {
        FAMILY_TEXT: {"FilterName": "HTML (StarWriter)"},
        FAMILY_SPREADSHEET: {"FilterName": "HTML (StarCalc)"},
        FAMILY_PRESENTATION: {"FilterName": "impress_html_Export"}
    },
    "odt": {
        FAMILY_TEXT: {"FilterName": "writer8"},
        FAMILY_WEB: {"FilterName": "writerweb8_writer"}
    },
    "doc": {
        FAMILY_TEXT: {"FilterName": "MS Word 97"}
    },
    "rtf": {
        FAMILY_TEXT: {"FilterName": "Rich Text Format"}
    },
    "txt": {
        FAMILY_TEXT: {
            "FilterName": "Text",
            "FilterOptions": "utf8"
        }
    },
    "ods": {
        FAMILY_SPREADSHEET: {"FilterName": "calc8"}
    },
    "xls": {
        FAMILY_SPREADSHEET: {"FilterName": "MS Excel 97"}
    },
    "csv": {
        FAMILY_SPREADSHEET: {
            "FilterName": "Text - txt - csv (StarCalc)",
            "FilterOptions": "44,34,0"
        }
    },
    "odp": {
        FAMILY_PRESENTATION: {"FilterName": "impress8"}
    },
    "ppt": {
        FAMILY_PRESENTATION: {"FilterName": "MS PowerPoint 97"}
    },
    "swf": {
        FAMILY_DRAWING: {"FilterName": "draw_flash_Export"},
        FAMILY_PRESENTATION: {"FilterName": "impress_flash_Export"}
    }
}

PAGE_STYLE_OVERRIDE_PROPERTIES = {
    FAMILY_SPREADSHEET: {
        # --- Scale options: uncomment 1 of the 3 ---
        # a) 'Reduce / enlarge printout': 'Scaling factor'
        "PageScale": 100,
        # b) 'Fit print range(s) to width / height': 'Width in pages' and 'Height in pages'
        # "ScaleToPagesX": 1, "ScaleToPagesY": 1000,
        # c) 'Fit print range(s) on number of pages': 'Fit print range(s) on number of pages'
        # "ScaleToPages": 1,
        "PrintGrid": False
    }
}


# -------------------#
# Configuration End #
# -------------------#

class DocumentConversionException(Exception):
    def __init__(self, message):
        self.message = message

    def __str__(self):
        return self.message


class DocumentConverter:
    def __init__(self, port=DEFAULT_OPENOFFICE_PORT):
        localContext = uno.getComponentContext()
        resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver",
                                                                         localContext)
        try:
            context = resolver.resolve("uno:socket,host=localhost,port=%s;urp;StarOffice.ComponentContext" % port)
        except NoConnectException:
            raise DocumentConversionException, "failed to connect to OpenOffice.org on port %s" % port
        self.desktop = context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", context)

    def convert(self, inputFile, outputFile):

        inputUrl = self._toFileUrl(inputFile)
        outputUrl = self._toFileUrl(outputFile)

        loadProperties = {"Hidden": True}
        inputExt = self._getFileExt(inputFile)
        if IMPORT_FILTER_MAP.has_key(inputExt):
            loadProperties.update(IMPORT_FILTER_MAP[inputExt])

        document = self.desktop.loadComponentFromURL(inputUrl, "_blank", 0, self._toProperties(loadProperties))
        try:
            document.refresh()
        except AttributeError:
            pass

        family = self._detectFamily(document)
        self._overridePageStyleProperties(document, family)

        outputExt = self._getFileExt(outputFile)
        storeProperties = self._getStoreProperties(document, outputExt)

        try:
            document.storeToURL(outputUrl, self._toProperties(storeProperties))
        finally:
            document.close(True)

    def _overridePageStyleProperties(self, document, family):
        if PAGE_STYLE_OVERRIDE_PROPERTIES.has_key(family):
            properties = PAGE_STYLE_OVERRIDE_PROPERTIES[family]
            pageStyles = document.getStyleFamilies().getByName('PageStyles')
            for styleName in pageStyles.getElementNames():
                pageStyle = pageStyles.getByName(styleName)
                for name, value in properties.items():
                    pageStyle.setPropertyValue(name, value)

    def _getStoreProperties(self, document, outputExt):
        family = self._detectFamily(document)
        try:
            propertiesByFamily = EXPORT_FILTER_MAP[outputExt]
        except KeyError:
            raise DocumentConversionException, "unknown output format: '%s'" % outputExt
        try:
            return propertiesByFamily[family]
        except KeyError:
            raise DocumentConversionException, "unsupported conversion: from '%s' to '%s'" % (family, outputExt)

    def _detectFamily(self, document):
        if document.supportsService("com.sun.star.text.WebDocument"):
            return FAMILY_WEB
        if document.supportsService("com.sun.star.text.GenericTextDocument"):
            # must be TextDocument or GlobalDocument
            return FAMILY_TEXT
        if document.supportsService("com.sun.star.sheet.SpreadsheetDocument"):
            return FAMILY_SPREADSHEET
        if document.supportsService("com.sun.star.presentation.PresentationDocument"):
            return FAMILY_PRESENTATION
        if document.supportsService("com.sun.star.drawing.DrawingDocument"):
            return FAMILY_DRAWING
        raise DocumentConversionException, "unknown document family: %s" % document

    def _getFileExt(self, path):
        ext = splitext(path)[1]
        if ext is not None:
            return ext[1:].lower()

    def _toFileUrl(self, path):
        return uno.systemPathToFileUrl(abspath(path))

    def _toProperties(self, dict):
        props = []
        for key in dict:
            prop = PropertyValue()
            prop.Name = key
            prop.Value = dict[key]
            props.append(prop)
        return tuple(props)


# def pdf2jpeg(pdf_input_path, jpeg_output_path="1.jpg"):
#     args = ["pdf2jpeg", # actual value doesn't matter
#             "-dNOPAUSE",
#             "-sDEVICE=jpeg",
#             "-r144",
#             "-sOutputFile=" + jpeg_output_path,
#             pdf_input_path]
#     x = ghostscript.Ghostscript("123.pdf")
#     x.exit()
#
#
# pdf2jpeg("123.pdf")


class Office2jpg():
    """
    openoffice -accept="socket,host=localhost,port=2002;urp;StarOffice.ServiceManager"
    or
    /usr/bin/openoffice -accept="socket,host=localhost,port=8100;urp;StarOffice.ServiceManager" -norestore -nofirstwizard -nologo -headless
    """
    def __init__(self,file,out_file,huanchun_dir="."):
        self.document = None


        self.dirname = ""
        self.dir_file_name = ""
        self.base_file_name = ""
        self.file_name_root = ""
        self.file_name_extension = ""

        self.out_file = out_file
        self.offoce_file2 = file
        self.huanchun_dir = huanchun_dir

        self.offoce_file = "file://"  # file:///home/lucas/myfile.docx
        self.pdf_file = "file://"
        self.pdf_file2 = ""
        self.jpg_file = "file://"
        self.local = uno.getComponentContext()
        resolver = self.local.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", self.local)
        self.context = resolver.resolve("uno:socket,host=localhost,port=8100;urp;StarOffice.ComponentContext")
        self.desktop = self.context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", self.context)
        self.document = self.desktop.getCurrentComponent()
        self.huanchun = self.huanchun_dir + os.sep + "huan_cun_lc"
        if not os.path.isdir(self.huanchun):
            os.makedirs(self.huanchun)

    def path_split(self):
        self.dir_file_name, self.base_file_name = os.path.split(self.offoce_file2)
        print self.dir_file_name, "---", self.base_file_name
        self.file_name_root, self.file_name_extension = os.path.splitext(self.base_file_name)
        print self.file_name_root, "---", self.file_name_extension
        if self.file_name_extension == ".pdf":
            self.pdf_file2 = self.out_file
        else:
            self.pdf_file2 = self.huanchun + os.sep + self.file_name_root + ".pdf"
    def office2pdf(self):
        """
         document = desktop.loadComponentFromURL("file:///c:"+filepath+".odt" ,"_blank", 0, ())
        document.store() # save
        document.storeAsURL("file:///home/lucas/myfile2.odt",()) # Save file as
        document.dispose() # exit
        """
        self.path_split()
        self.document = self.document.loadComponentFromURL(self.offoce_file, "_blank", 0, ())
        self.property = (PropertyValue("FilterName", 0, "writer_pdf_Export", 0),)
        self.document.storeToURL("file:///home/lucas/myfile2.pdf", self.property)
        self.document.dispose()

    def office2pdf2(self):

        converter = DocumentConverter()
        converter.convert(self.offoce_file2, self.pdf_file2)

    def pdf2jpeg(self):
        save_jpg_dir = self.out_file + os.sep + self.file_name_root
        if not os.path.isdir(save_jpg_dir):
            os.makedirs(save_jpg_dir)
        jpg_dir = save_jpg_dir + os.sep + "%.3ld.png"
        print jpg_dir
        args = ["pdf2jpeg",  # actual value doesn't matter
                "-dNOPAUSE",
                "-sDEVICE=jpeg",
                "-r144",
                "-sOutputFile=" + jpg_dir,
                self.pdf_file2]
        x = ghostscript.Ghostscript(*args)
        x.exit()

    def run(self):
        self.path_split()
        if self.file_name_extension == ".pdf":
            self.pdf_file2 = self.out_file
            self.pdf2jpeg()
        else:
            self.office2pdf2()
            self.pdf2jpeg()



#




